﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using ISolutions.SharePoint.Mui.Impl;
using System.Web.UI.HtmlControls;

namespace ISolutions.SharePoint.Mui.Controls
{
    public abstract class TabbedMuiControl : MuiControl
    {
        /// <summary>
        /// Gets a value indicating whether the field value should be rendered or the editable tab control.
        /// </summary>
        /// <value><c>true</c> if the field's value should be rendered; otherwise, <c>false</c>, if the edit controls are to be rendered.</value>
        protected virtual bool ShouldRenderValue
        {
            get
            {
                return SPContext.Current.FormContext.FormMode == SPControlMode.Display;
            }
        }

        /// <summary>
        /// Outputs the field's value when ShouldRenderValue is true, otherwise renders the control (i.e. the tab control). 
        /// Outputs server control content to a provided <see cref="T:System.Web.UI.HtmlTextWriter"/> object and stores tracing information about the control if tracing is enabled.
        /// </summary>
        /// <param name="writer">The <see cref="T:System.Web.UI.HTmlTextWriter"/> object that receives the control content.</param>
        public override void RenderControl(System.Web.UI.HtmlTextWriter writer)
        {
            try
            {
                if (ShouldRenderValue)
                {
                    writer.Write(GetLocalizedContent());
                }
                else
                {
                    base.RenderControl(writer);
                }

            }
            catch (Exception ex)
            {
                HandleException(ex);
            }
            RenderExceptions(writer);
        }


        /// <summary>
        /// If ShouldRenderValue is false, creates a tab container with an edit control for each language.
        /// Called by the ASP.NET page framework to notify server controls that use composition-based implementation to create any child controls they contain in preparation for posting back or rendering.
        /// </summary>
        protected override void CreateChildControls()
        {
            try
            {
                base.CreateChildControls();
                
                if (!ShouldRenderValue)                
                {
                    // Create update panel with tabs for each language
                    CreateEditChildControls();
                }
            }
            catch (Exception ex)
            {
                HandleException(ex);
            }
        }

        private void CreateEditChildControls()
        {
            HtmlGenericControl outerDiv = new HtmlGenericControl("div");
            outerDiv.Attributes.Add("id", String.Format("tab{0}", FieldName.ToLower()));
            Controls.Add(outerDiv);

            // build tab selector
            CreateTabSelector(outerDiv);

            // create edit elements for each language
            CreateTabEditZone(outerDiv);

            RegisterTabScript();
        }

        private void RegisterTabScript()
        {
            Page.ClientScript.RegisterStartupScript(
                GetType(),
                String.Format("Tab{0}", FieldName),
                String.Format("var tab{0}=new ddtabcontent(\"tab{0}\"); tab{0}.init();", FieldName.ToLower()),
                true);
        }

        private void CreateTabEditZone(HtmlGenericControl outerDiv)
        {
            foreach (KeyValuePair<string, string> item in MuiHelper.GetLanguages())
            {
                HtmlGenericControl editorDiv = new HtmlGenericControl("div");
                editorDiv.Attributes.Add("class", "tabcontent");
                editorDiv.Attributes.Add("id", String.Format("language{0}{1}", FieldName.ToLower(), item.Key));
                outerDiv.Controls.Add(editorDiv);

                FieldMetadata editControl = CreateEditControl();
                editControl.FieldName = ((item.Key == MuiHelper.GetDefaultLanguage()) ?
                    FieldName :
                    string.Format("{0}_{1}", FieldName, item.Key));
                editControl.ListId = SPContext.Current.ListItem.ParentList.ID;
                editControl.ItemId = SPContext.Current.ListItem.ID;
                editControl.ControlMode = SPContext.Current.FormContext.FormMode;

                editorDiv.Controls.Add(editControl);
            }
        }

        private void CreateTabSelector(HtmlGenericControl outerDiv)
        {
            HtmlGenericControl tabSelector = new HtmlGenericControl("ul");
            tabSelector.Attributes.Add("class", "shadetabs");
            outerDiv.Controls.Add(tabSelector);

            foreach (KeyValuePair<string, string> item in MuiHelper.GetLanguages())
            {
                HtmlGenericControl li = new HtmlGenericControl("li");
                tabSelector.Controls.Add(li);

                HtmlGenericControl anchor = new HtmlGenericControl("a");
                anchor.Attributes.Add("rel", String.Format("language{0}{1}", FieldName.ToLower(), item.Key));
                anchor.Attributes.Add("href", "#");
                anchor.InnerText = item.Value;
                li.Controls.Add(anchor);
            }
        }

        /// <summary>
        /// Creates the edit control. This method is called once for each language. 
        /// The FieldName, ListId, ItemId and ControlMode properties are set by this class.
        /// </summary>
        /// <returns>A control instance used to edit the field value for one language.</returns>
        protected abstract FieldMetadata CreateEditControl();
    }
}